using B.S.Requst;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
using B.S.Domain.InvoiceManagement;
using B.S.Infratrctrue;
using B.S.Data.MES.API.Dto.InvoiceDTO;
using Microsoft.EntityFrameworkCore;

namespace B.S.Data.MES.API.Applications.B.S.KApplications.Query.InvoiceReceiptQuery
{
    /// <summary>
    /// 获取到票详情查询处理程序
    /// 处理到票信息的详情查询逻辑
    /// </summary>
    public class GetInvoiceReceiptDetailQueryHandler : IRequestHandler<GetInvoiceReceiptDetailQuery, APIRequst<InvoiceReceiptDTO>>
    {
        private readonly IBaseRepository<InvoiceReceipt> _invoiceReceiptRepository;
        private readonly IBaseRepository<SalesInvoice> _salesInvoiceRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="invoiceReceiptRepository">到票仓储</param>
        /// <param name="salesInvoiceRepository">销售发票仓储</param>
        public GetInvoiceReceiptDetailQueryHandler(
            IBaseRepository<InvoiceReceipt> invoiceReceiptRepository,
            IBaseRepository<SalesInvoice> salesInvoiceRepository)
        {
            _invoiceReceiptRepository = invoiceReceiptRepository;
            _salesInvoiceRepository = salesInvoiceRepository;
        }

        /// <summary>
        /// 处理获取到票详情的查询
        /// </summary>
        /// <param name="request">获取到票详情查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果，包含到票详情</returns>
        public async Task<APIRequst<InvoiceReceiptDTO>> Handle(GetInvoiceReceiptDetailQuery request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证参数
                if (request.ReceiptId <= 0)
                {
                    return new APIRequst<InvoiceReceiptDTO> { Code = RequstCode.失败, Msg = "到票记录ID不能为空" };
                }

                // 查询到票记录
                var invoiceReceipt = await _invoiceReceiptRepository.GetAll().FirstOrDefaultAsync(s => s.ReceiptId == request.ReceiptId && !s.isDel);
                if (invoiceReceipt == null)
                {
                    return new APIRequst<InvoiceReceiptDTO> { Code = RequstCode.失败, Msg = "到票记录不存在" };
                }

                // 查询关联的发票信息
                var invoice = await _salesInvoiceRepository.GetAll().FirstOrDefaultAsync(i => i.InvoiceId == invoiceReceipt.InvoiceId && !i.isDel);

                // 转换为DTO
                var dto = new InvoiceReceiptDTO
                {
                    ReceiptId = invoiceReceipt.ReceiptId,
                    InvoiceId = invoiceReceipt.InvoiceId,
                    InvoiceNo = invoice?.InvoiceNo ?? string.Empty,
                    ReceiptDate = invoiceReceipt.ReceiptDate,
                    ReceiptAmount = invoiceReceipt.ReceiptAmount,
                    ReceiptStatus = invoiceReceipt.ReceiptStatus,
                    ReceiptStatusName = GetReceiptStatusName(invoiceReceipt.ReceiptStatus),
                    PaymentMethod = invoiceReceipt.PaymentMethod,
                    TransactionNo = invoiceReceipt.TransactionNo,
                    Remarks = invoiceReceipt.Remarks,
                    CreateName = invoiceReceipt.CreateName,
                    CreateTime = invoiceReceipt.CreateTime ?? DateTime.Now,
                    UpdateName = invoiceReceipt.UpdateName,
                    UpdateTime = invoiceReceipt.UpdateTime ?? DateTime.Now
                };

                return new APIRequst<InvoiceReceiptDTO>
                {
                    Code = RequstCode.成功,
                    Msg = "查询成功",
                    Data = dto
                };
            }
            catch (Exception ex)
            {
                // 记录异常并返回失败结果
                return new APIRequst<InvoiceReceiptDTO>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取到票状态名称
        /// </summary>
        /// <param name="status">到票状态值</param>
        /// <returns>到票状态名称</returns>
        private string GetReceiptStatusName(int status)
        {
            switch (status)
            {
                case 0:
                    return "部分到票";
                case 1:
                    return "全部到票";
                case 2:
                    return "未到票";
                default:
                    return "未知";
            }
        }
    }
}